template <typename T>
class UnionFindSet
{
public:
    UnionFindSet()
    {
    }

    template <typename TContainer>
    UnionFindSet(const TContainer &container)
    {
        auto begin = container.begin();
        auto end = container.end();
        while (begin != end)
        {
            m[*begin] = *begin;
            ++begin;
        }
    }

    void insert(const T &value)
    {
        if (!m.count(value))
        {
            m[value] = value;
        }
    }

    bool exist(const T &value)
    {
        return m.count(value);
    }

    T find(const T &value)
    {
        if (m[value] == value)
        {
            return value;
        }
        return m[value] = find(m[value]);
    }

    void join(const T &value1, const T &value2)
    {
        if (find(value1) != find(value2))
        {
            m[find(value1)] = find(value2);
        }
    }

private:
    std::unordered_map<T, T> m;
};

class Solution
{
public:
    int swimInWater(vector<vector<int>> &grid)
    {
        int n = grid.size();
        vector<vector<int>> sortedGridId(n * n);
        for (int i = 0; i < n; ++i)
        {
            for (int j = 0; j < n; ++j)
            {
                sortedGridId[grid[i][j]] = {i, j};
            }
        }

        UnionFindSet<int> ufs;
        for (int i = 0; i < n * n; ++i)
        {
            ufs.insert(i);
        }

        int start = grid[0][0];
        int target = grid[n - 1][n - 1];
        int time = 0;
        while (ufs.find(start) != ufs.find(target))
        {
            ++time;
            int x = sortedGridId[time][0];
            int y = sortedGridId[time][1];
            if (x > 0 && grid[x - 1][y] <= time)
            {
                ufs.join(grid[x][y], grid[x - 1][y]);
            }
            if (x < n - 1 && grid[x + 1][y] <= time)
            {
                ufs.join(grid[x][y], grid[x + 1][y]);
            }
            if (y > 0 && grid[x][y - 1] <= time)
            {
                ufs.join(grid[x][y], grid[x][y - 1]);
            }
            if (y < n - 1 && grid[x][y + 1] <= time)
            {
                ufs.join(grid[x][y], grid[x][y + 1]);
            }
        }
        return time;
    }
};